package cn.wzptsoft.tinymallbe.service;

import cn.wzptsoft.common.exception.BizException;
import cn.wzptsoft.common.utils.MD5Utils;
import cn.wzptsoft.tinymallbe.dto.UserLoginDTO;
import cn.wzptsoft.tinymallbe.entity.User;
import cn.wzptsoft.tinymallbe.repository.UserRepository;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 登录用户
     *
     * @param userLoginDTO 用户登录请求数据
     * @return 登录成功-true  登录失败-false
     */
    public User login(UserLoginDTO userLoginDTO) {
        User user = userRepository.findByUsername(userLoginDTO.getUsername());
        if (user == null) {
            throw new BizException("登录失败：用户名或密码不正确");
        }
        String md5Password = MD5Utils.md5Digest(userLoginDTO.getPassword(), user.getSalt());
        if (!md5Password.equals(user.getPassword())) {
            throw new BizException("登录失败：用户名或密码不正确");
        }
        return user;
    }

    public User getUserById(long id) {
        return userRepository.findFirstById(id);
    }
}
